package com.family.pedigree.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.family.pedigree.domain.FamilyUserIncome;
import com.family.pedigree.domain.FamilyUserInsurance;
import com.family.pedigree.domain.common.KeyValues;
import com.family.pedigree.mapper.FamilyUserIncomeMapper;
import com.family.pedigree.service.IFamilyUserIncomeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 个人收入表 服务实现类
 * </p>
 *
 * @author forever
 * @since 2025-01-16
 */
@Service
public class FamilyUserIncomeServiceImpl extends ServiceImpl<FamilyUserIncomeMapper, FamilyUserIncome> implements IFamilyUserIncomeService {

    @Override
    public List<KeyValues> findAvgIncome() {

        List<KeyValues> list = CollUtil.newArrayList();
        for (int i = 0; i < 5; i++) {
            int year = 2025 - i;
            KeyValues vo = new KeyValues();
            vo.setKeyA(year + "");
            LocalDate now = LocalDate.of(year, 1, 1);
            List<FamilyUserIncome> result = list(Wrappers.<FamilyUserIncome>lambdaQuery()
                    .ge(FamilyUserIncome::getParticularYear, now)
                    .lt(FamilyUserIncome::getParticularYear, LocalDate.of(year + 1, 1, 1)));
            if (CollUtil.isNotEmpty(result)) {
                BigDecimal total = result.stream().map(FamilyUserIncome::getAnnualIncome).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                vo.setValueA(total.divide(BigDecimal.valueOf(result.size()), RoundingMode.HALF_UP));
            }
            list.add(vo);

        }
        list.sort(Comparator.comparing(KeyValues::getKeyA));
        return list;
    }
}
